import baseconfig from '@/config.js'
import { getToken } from './storageUtils.js'
const http = {
	request(config) {
		config = beforRequest(config)
		if (config == null) return
		config.url = baseconfig.api_url + config.url
		return new Promise((resolve, reject) => {
			uni.request(config)
				.then(res => {
					let { data } = res
					const response = beforResponse(data)
					resolve(response)
				})
				.catch(err => {
					errHandle(err)
					reject(err)
				})
		})
	},
	upload(config) {
		config.url = baseconfig.api_url + config.url
		console.log(config)
		return new Promise((resolve, reject) => {
			uni.uploadFile(config)
				.then(res => {
					let { data } = res
					const response = JSON.parse(data)
					resolve(response)
				})
				.catch(err => {
					errHandle(err)
					reject(err)
				})
		})

	},
	uploadFile(url, filedata, data) {
		var token = getToken()
		var files = filedata ? [{ name: filedata.name, uri: filedata.url }] : null

		var _path = filedata ? filedata.url : null
		console.log("_path",_path)
		return this.upload({
			url: url,
			files: files,
			name: 'file',
			filePath: _path,
			formData: data,
			header: { 'selftoken': token },
		})
	},
	postfile(url, filedata, info) {
		var token = getToken()
		var _path = filedata ? filedata[0].uri : null
		console.log(filedata)
		return this.upload({
			url: url,
			files: filedata,
			name: 'file',
			filePath: _path,
			formData: info,
			header: { 'selftoken': token },
		})
	},
	get(url, params) {
		return this.request({
			url: url,
			data: params,
			method: 'GET'
		})
	},
	get_nparm(url) {
		return this.request({
			url: url,
			method: 'GET'
		})
	},
	post(url, params) {
		return this.request({

			url: url,
			data: params,
			method: 'POST'
		})
	}
}
const beforRequest = config => {
	var token = getToken()
	if (token) {
		config.header = {
			'content-type': 'application/x-www-form-urlencoded',
			'selftoken': token
		}
	} else {
		config.header = { 'content-type': 'application/x-www-form-urlencoded' }
		if (config.url.indexOf('/user/') != -1) {
			uni.showModal({
				title: "温馨提醒",
				content: '登录已失效',
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({ url: '/pages/auth/login' })
					}
				}
			})
			return null
		}
	}
	if (config.data) {
		var _data = config.data
		var parm = {}
		for (var key in _data) {
			var _v = _data[key]
			if (_v !== null && _v !== undefined && _v !== '') {
				parm[key] = _v
			}
		}
		config.data = parm
	}

	return config
}
const beforResponse = response => {
	return response
}
const errHandle = err => {}
export default http